<?php

namespace app\api\controller\xmwechat;

use app\api\service\QueueOrder;
use app\common\controller\Frontend;
use app\common\library\xmwechat\payment\PartnerPayService;
use ba\Exception;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\Pay\Application;
use EasyWeChat\Pay\Message;
use think\facade\Db;
use think\facade\Log;
use think\Request;
use app\admin\model\alliance\Wallet;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\Goods AS GoodsModel;
use GuzzleHttp\Client;
use app\api\service\SendMsg;
use app\common\library\Feie;
/**
 * 合作伙伴（服务商模式支付）
 */
class PartnerPayment extends Frontend
{
    // 数组中的 pay、refunds 请在调试完成后删除，支付、退款接口需要登录
    protected array $noNeedLogin = ['pay', 'refunds', 'payNotify', 'refundsNotify','add','test'];

    protected array $partnerPaymentConfig;

    protected array $wechatPartnerConfig;

    public function initialize(): void
    {
        parent::initialize();
        $config                = config('xmwechat');
        $this->partnerPaymentConfig = $config['partnerPayment'];

        $this->wechatPartnerConfig = [
            'mch_id'      => $this->partnerPaymentConfig['sp_mchid'],
            'secret_key'  => $this->partnerPaymentConfig['secret_key'],
            'certificate' => root_path() . 'app/cert/partner/apiclient_cert.pem',
            'private_key' => root_path() . 'app/cert/partner/apiclient_key.pem',
            'notify_url'  => $this->partnerPaymentConfig['notify_url'],
            'http'        => [
                'throw'   => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
            ],
        ];
    }

    public function pay(Request $request): void
    {
        if ($request->isPost()) {
            $params = $request->only(['order_no', 'body', 'pay_price', 'openid', 'transaction_no']);
            $params['pay_type'] = 'miniProgram'; // miniProgram: 小程序支付； offiAccount： 公众号支付
            $result = PartnerPayService::getInstance()->pay($params);
            if ($result !== false) {
                $this->success('success', $result);
            } else {
                $this->error('error');
            }
        }
    }

    public function refunds(Request $request): void
    {
        if ($request->isPost()) {
            $params = $request->only(['pay_price', 'refund_price', 'out_trade_no','out_refund_no','reason']);
            $result = PartnerPayService::getInstance()->refunds($params);
            
            if ($result !== false) {
                $this->success('success', $result);
            } else {
                $this->error('error');
            }
        }
    }

    //支付回调
    public function payNotify()
    {
        try {
            $app    = new Application($this->wechatPartnerConfig);
            $server = $app->getServer();
            $server->handlePaid(function (Message $message, \Closure $next) use ($app) {
                $notifyData   = json_decode($message, true);
                $success_time = strtotime($notifyData['success_time']);
                $out_trade_no = $notifyData['out_trade_no'];

                Log::info('服务商支付回调来了' . json_encode($notifyData,JSON_UNESCAPED_UNICODE));

                // 查询订单
                $order = GoodsOrderModel::where('order_no', $out_trade_no)->find();
                if (!$order || $order['status'] == 2 || $order['status']==3) {
                    Log::info('订单不存在或者已经支付了');
                    return ['code' => 'SUCCESS', 'message' => '成功'];
                }
                
                elseif($notifyData['trade_state'] === 'SUCCESS'){
                    // $user = \app\admin\model\User::find($order->user_id);
                    // if ( $user->pid > 0){
                    //      \app\admin\model\broker\fen\Log::parentCommisson($user->pid,$order);
                    // }else{
                    //      \app\admin\model\broker\fen\Log::parentCommissonStore($order);
                    // }
                    //更新销量
                    
                    GoodsModel::where("id",$order->goods_id)->inc('sales',1)->update();
                    if($order->order_type == 2){
                        $order->out_trade_no = $notifyData['transaction_id'];
                        $order->pay_time = $success_time;
                        // $order->status = 3;
                        $order->save();
                        $model = new \app\admin\model\goods\Order();
                        $model->orderSuccess($order->id);
                    } elseif ($order->order_type == 1){
                        $order->out_trade_no = $notifyData['transaction_id'];
                        $order->pay_time = $success_time;
                        $order->status = 2;
                        $order->save();
                        
                    } elseif ($order->order_type == 3){
                        $order->out_trade_no = $notifyData['transaction_id'];
                        $order->pay_time = $success_time;
                        $order->save();
                        $model = new \app\admin\model\goods\Order();
                        $model->orderSuccess($order->id);
                        $app = new Feie();
                        $app->printMsg($order);
                    }
                    //订单排队
                    QueueOrder::addQueueOrder($order);


                    //音响播报到账
                    $sn = Db::name('store_pay')->where('store_id',  $order->store_id)->find()['sn'];
                    if(!empty($sn)){
                        SendMsg::send($out_trade_no,$order->goods_prices,$sn);
                    }

                    //获取商家类型
                    $Alliance = new \app\api\model\Alliance();
                    $store_type =$Alliance::where('id',$order->store_id)->value('type');
                    Log::info('商家类型'.$store_type);
                    $userModel = new \app\common\model\User();
                    $userModel->checkPid($order->user_id);
                }

                elseif ($message['result_code'] === 'FAIL') {
                    // 支付失败逻辑
                    return ['code' => 'ERROR', 'message' => '支付失败'];
                }

                return $next($message);
            });
            return $server->serve();
        } catch (InvalidArgumentException|RuntimeException|\ReflectionException|\Throwable $e) {
            Log::info('服务商微信支付回调通知：' . $e->getMessage());
        }
    }
    
    
    public function test(){
        // $Walletmodel  = new Wallet(); 
        $order = GoodsOrderModel::where('order_no', 'SP202411111000483357115')->find();
        $res = \app\admin\model\broker\fen\Log::parentCommisson(250,$order);
        dump($res);die();
    }














}
